<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import logger from '@/utils/logger'
import { saveGoodsSales } from '@/api/goodsSales'
import StockSelector from './StockSelector.vue'
import { useUserStore } from '@/stores/user'
import { formatDateTime, getNowDateTime } from '@/utils/dayjs'
import { generateSalesOrderNo } from '@/utils/generateOrderNo'
import { getStatusType, getStatusText, REQUEST_STATE } from '@/constants'

const emit = defineEmits(['success', 'close'])

// props接收参数
const props = defineProps({
  initialData: {
    type: Object,
    default: null,
  },
  isReview: {
    type: Boolean,
    default: false,
  },
  isDetail: {
    type: Boolean,
    default: false,
  },
})

// 引入用户store，获取当前登录用户
const userStore = useUserStore()
const currentUser = computed(() => userStore.nickname || '未登录')

// 控制商品选择器对话框显示
const selectorVisible = ref(false)

// 创建默认表单数据的函数，避免重复定义
const createDefaultFormData = () => ({
  salesRequestMId: generateSalesOrderNo(), // 上架单ID，使用自动生成的单号
  dealerId: userStore.dealerId || '', // 供应商ID
  dealerOperatorId: userStore.operatorId || '', // 供应商操作员ID
  requestTime: getNowDateTime(), // 申请时间，使用后端要求的格式
  requestState: 0, // 申请状态：0-未提交审核（本地草稿）
  adminId: '', // 工会审核人ID
  checkTime: '', // 审核时间
  comments: '', // 审核意见
  editType: 0, // 编辑类型：0-供应商新增
  dealer: userStore.dealerName || '', // 供应商名称
  nickname: currentUser.value, // 供应商操作员名称
  adminName: '', // 工会审核人名称
  pzSalesRequestDList: [], // 商品明细列表
})

// 表单数据
const formData = ref(createDefaultFormData())

// 已选择的商品列表，用于商品选择器v-model
const selectedGoods = ref([])

// 监听商品选择器的选中项变化，同步到表单明细列表
watch(selectedGoods, (newVal) => {
  // 先把已存在的明细做成 Map，方便复用用户已填写的数据
  const existingMap = new Map(
    formData.value.pzSalesRequestDList.map((item) => [item.dealerGoodsStoreId, item]),
  )

  // 根据最新的选中商品生成新的明细列表
  const newList = newVal.map((good) => {
    const cached = existingMap.get(good.dealerGoodsStoreId)
    if (cached) return cached
    return {
      salesRequestDId: '', // 明细ID，新增时为空
      salesRequestMId: formData.value.salesRequestMId, // 主表ID
      dealerGoodsStoreId: good.dealerGoodsStoreId, // 商品库存ID
      isSale: true, // 默认允许上架
      notes: '', // 备注
      goodsTypeName: good.dealerGoodsTypeName || '', // 商品类别名称
      xzqhName: good.xzqhName || '', // 商品专属区域
      goodsName: good.goodsName || '', // 商品名称
      goodsPicture: good.goodsPicture || '', // 商品图片
      specifications: good.specifications || '', // 商品规格
      unit: good.unit || '', // 商品单位
      introduce: good.introduce || '', // 商品介绍
      address: good.address || '', // 商品产地
      periodStartingDate: good.periodStartingDate || '', // 有效期开始日期
      periodEndDate: good.periodEndDate || '', // 有效期结束日期
      points: good.points || 0, // 单个商品兑换积分
      quantity: good.quantity || 0, // 商品库存数量
      points: good.unitPrice || 0,
      shippingFee: good.shippingFee || 0, // 配送费
      freeShipping: good.freeShipping || 0, // 免配送费数量
    }
  })

  formData.value.pzSalesRequestDList = newList
})

// 表单验证规则
const rules = {
  pzSalesRequestDList: [
    { required: true, type: 'array', min: 1, message: '至少添加一件商品', trigger: 'change' },
  ],
  salesRequestMId: [
    { required: true, message: '上架单号不能为空', trigger: 'blur' },
    { min: 1, message: '上架单号不能为空', trigger: 'blur' },
  ],
}

const formRef = ref(null)

// 初始化数据，用于编辑模式
const initFormData = () => {
  if (props.initialData) {
    formData.value = { ...props.initialData }

    // 如果有明细数据，同步到选中商品列表
    if (formData.value.pzSalesRequestDList && formData.value.pzSalesRequestDList.length > 0) {
      selectedGoods.value = [...formData.value.pzSalesRequestDList]
    }
  } else {
    formData.value = createDefaultFormData()
    selectedGoods.value = []
  }
}

// 打开商品选择器
const openStockSelector = () => {
  selectorVisible.value = true
}

// 移除商品
const removeGoods = (index) => {
  // 获取要删除的商品ID
  const goodsToRemove = formData.value.pzSalesRequestDList[index]
  formData.value.pzSalesRequestDList.splice(index, 1)

  // 同步更新selectedGoods，确保商品选择器显示正确的选中状态
  selectedGoods.value = selectedGoods.value.filter(
    (item) => String(item.dealerGoodsStoreId) !== String(goodsToRemove.dealerGoodsStoreId),
  )
}

// 验证表单数据
const validateForm = async () => {
  if (!formRef.value) return false

  // 检查上架单号是否为空
  if (!formData.value.salesRequestMId?.trim()) {
    ElMessage.warning('上架单号不能为空')
    return false
  }

  // 检查是否添加了商品
  if (!formData.value.pzSalesRequestDList?.length) {
    ElMessage.warning('请至少添加一件商品')
    return false
  }

  // 表单验证
  const valid = await formRef.value
    .validate()
    .then(() => true)
    .catch(() => false)
  return valid
}

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  const valid = await validateForm()
  if (!valid) return

  try {
    const loading = ElLoading.service({
      lock: true,
      text: '正在保存...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    // 确保日期格式正确
    const requestTime =
      formData.value.requestTime && typeof formData.value.requestTime !== 'string'
        ? formatDateTime(formData.value.requestTime, 'YYYY-MM-DD HH:mm')
        : formData.value.requestTime

    // 如果是审核模式，设置editType为2（供应商-提交）
    if (props.isReview) {
      formData.value.editType = 2
    } else if (props.initialData) {
      // 如果是编辑模式（从initialData传入），设置editType为1
      formData.value.editType = 1
    } else {
      // 如果是新增模式，设置editType为0
      formData.value.editType = 0
    }

    // 只提取后端需要的字段
    const submitData = {
      salesRequestMId: formData.value.salesRequestMId,
      dealerId: formData.value.dealerId,
      dealerOperatorId: formData.value.dealerOperatorId,
      requestTime: requestTime,
      requestState: formData.value.requestState,
      editType: formData.value.editType,
      pzSalesRequestDList: formData.value.pzSalesRequestDList.map((item) => ({
        salesRequestMId: formData.value.salesRequestMId,
        dealerGoodsStoreId: item.dealerGoodsStoreId,
        isSale: item.isSale,
        notes: item.notes || '',
      })),
    }

    const res = await saveGoodsSales(submitData)

    loading.close()

    if (res.success) {
      ElMessage.success(
        props.isReview ? '提交审核成功' : formData.value.salesRequestMId ? '编辑成功' : '添加成功',
      )
      emit('success')
      emit('close')
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    logger.error('保存上架单据失败', error)
    ElMessage.error('保存失败')
  }
}

// 取消
const handleCancel = () => {
  emit('close')
}

// 初始化
watch(
  () => props.initialData,
  () => {
    initFormData()
  },
  { immediate: true },
)
</script>

<template>
  <!-- 商品选择器对话框 -->
  <el-dialog v-model="selectorVisible" title="选择商品" width="80%" destroy-on-close align-center>
    <StockSelector v-model="selectedGoods" @close="selectorVisible = false" />
  </el-dialog>

  <div class="sales-container">
    <div class="receipt-header">
      <div class="receipt-title">
        {{ props.isDetail ? '商品上架单详情' : props.isReview ? '商品上架审核' : '商品上架申请单' }}
      </div>
      <div class="receipt-no">
        <span class="label">NO:</span>
        <el-input
          v-model="formData.salesRequestMId"
          placeholder="单号已自动生成，可修改"
          class="no-input"
          :disabled="formData.requestState !== 0 || props.isReview || props.isDetail"
        />
      </div>
    </div>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto" class="sales-form">
      <!-- 上架单基本信息 -->
      <div class="form-row">
        <el-form-item label="操作员">
          <el-input v-model="formData.nickname" disabled />
        </el-form-item>
        <el-form-item label="申请时间">
          <el-input :value="formatDateTime(formData.requestTime, 'YYYY-MM-DD HH:mm')" disabled />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="getStatusType(formData.requestState)">
            {{ getStatusText(formData.requestState) }}
          </el-tag>
        </el-form-item>
      </div>
      <div class="form-row">
        <el-form-item label="审核人">
          <el-input v-model="formData.adminName" disabled placeholder="审核后自动填写" />
        </el-form-item>
        <el-form-item label="审核时间">
          <el-input
            :value="formatDateTime(formData.checkTime, 'YYYY-MM-DD HH:mm')"
            disabled
            placeholder="审核后自动填写"
          />
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input v-model="formData.comments" disabled placeholder="审核后自动填写" />
        </el-form-item>
      </div>
    </el-form>

    <!-- 商品列表 -->
    <div class="goods-section">
      <div class="section-header">
        <h3>商品列表</h3>
        <el-button
          v-if="formData.requestState === 0 && !props.isReview && !props.isDetail"
          type="primary"
          @click="openStockSelector"
        >
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          添加商品
        </el-button>
      </div>

      <el-table :data="formData.pzSalesRequestDList" style="width: 100%" class="goods-table">
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 60px; height: 60px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsName"
          show-overflow-tooltip
          label="商品名称"
          min-width="180"
          align="center"
        />
        <el-table-column prop="goodsTypeName" label="商品类别" min-width="120" align="center" />
        <el-table-column prop="specifications" label="规格" min-width="100" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column label="有效期" min-width="200" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.periodStartingDate, 'YYYY-MM-DD') }} 至
            {{ formatDateTime(row.periodEndDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存数量" width="100" align="center" />
        <el-table-column prop="points" label="单价（元）" width="100" align="center" />
        <el-table-column prop="shippingFee" label="配送费（元）" width="120" align="center">
          <template #default="{ row }">
            {{ row.shippingFee || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="freeShipping" label="免配送费数量" width="130" align="center">
          <template #default="{ row }">
            {{ row.freeShipping || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="是否上架" width="200" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.isSale"
              :disabled="formData.requestState !== 0 || props.isReview || props.isDetail"
              active-text="上架"
              inactive-text="不上架"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="150" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.notes"
              placeholder="请输入备注"
              :disabled="formData.requestState !== 0 || props.isReview || props.isDetail"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="80"
          align="center"
          v-if="formData.requestState === 0 && !props.isReview && !props.isDetail"
        >
          <template #default="{ $index }">
            <el-button type="danger" circle @click="removeGoods($index)">
              <template #icon>
                <el-icon><LineMdTrash /></el-icon>
              </template>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <!-- 详情模式：只显示关闭按钮 -->
      <template v-if="props.isDetail">
        <el-button @click="handleCancel">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          关闭
        </el-button>
      </template>

      <!-- 编辑模式：显示取消和保存按钮 -->
      <template v-else-if="!props.isReview">
        <el-button @click="handleCancel">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :disabled="![REQUEST_STATE.DRAFT, REQUEST_STATE.REJECTED].includes(formData.requestState)"
        >
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          保存
        </el-button>
      </template>

      <!-- 审核模式：显示取消和审核按钮 -->
      <template v-else>
        <el-button @click="handleCancel">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="success" @click="handleSubmit">
          <template #icon>
            <el-icon><LineMdUpload /></el-icon>
          </template>
          审核
        </el-button>
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.sales-container {
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
}

.receipt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  flex: 0 0 auto;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: -10px;
    height: 1px;
    border-radius: 10px;
    background-color: #cbcbcb;
  }

  .receipt-title {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .receipt-no {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 8px;

    .label {
      font-weight: bold;
      font-size: 16px;
    }

    .no-input {
      width: 200px;
    }
  }
}

.sales-form {
  flex: 0 0 auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.form-row {
  display: flex;
  gap: 20px;
  :deep(.el-form-item) {
    flex: 1;
    margin-bottom: 0;
  }
}

.goods-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: auto;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      font-size: 18px;
      margin: 0;
      color: #303133;
    }
  }

  .no-image {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    background-color: #f5f7fa;
    font-size: 12px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
  }
}

.goods-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.footer-actions {
  flex: 0 0 auto;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
